#!/usr/bin/env python

'''
http://support.trendmicro.com.cn/Anti-Virus/Main-Pattern/lpt$vpn_747.zip
wget -b -v http://support.trendmicro.com.cn/Anti-Virus/Main-Pattern/lpt\$vpn_767.zip -O lptvpn.zip
'''
import os
import re
import subprocess
import urllib
import urlparse

PATTERN_TYPE = 'CHINA'

VIRUS_ROOT_LINK = 'http://support.trendmicro.com.cn/'
RE_VIRUS_PATTERN_OBJ = re.compile('''Anti-Virus/China-Pattern/Pattern/lpt\$vpn_\d{3}.zip''')

VIRUS_PATTERN_PAGE = '''http://support.trendmicro.com.cn/Anti-Virus/China-Pattern/Pattern/'''
BLACKLIST_PAGE = '''http://support.trendmicro.com.cn/Anti-Virus/Main-Pattern/'''

WGET = 'wget'
UNZIP = 'unzip'

def read_page(u):
    #print urlparse.urljoin(VIRUS_ROOT_LINK, VIRUS_PATTERN_PAGE)
    try:
        f = urllib.urlopen(urlparse.urljoin(VIRUS_ROOT_LINK, VIRUS_PATTERN_PAGE))
        res =  f.read()
    except IOError:
        return False
    else:
        f.close()
    return res

def match_virus_pattern_link(s):
    if RE_VIRUS_PATTERN_OBJ.search(s):
        path = RE_VIRUS_PATTERN_OBJ.search(s).group()
        return urlparse.urljoin(VIRUS_ROOT_LINK, path)
    else:
        return False
    
def get_virus_pattern(l):
    c = '''%s %s -c -b -v  -O lptvpn.zip''' % (WGET, l)
    #os.system(c)
    wget_return_code = subprocess.call(['%s' % WGET, '%s' % l, '-v', '-O', 'lptvpn.zip'])
    
def deploy_pattern():
    unzip_return_code = subprocess.call(['%s' % UNZIP, '-o', 'lptvpn.zip', '-d', '/etc/iscan/'])
    kill_return_code = subprocess.call(['killall', '-HUP', 'havp'])

def main():
    print 'Trend Virus Pattern File Updater'
    r = read_page(VIRUS_PATTERN_PAGE)
    pattern_link =  match_virus_pattern_link(read_page(VIRUS_PATTERN_PAGE))
    print 'Last Pattenr Link: %s' % pattern_link
    print 'Starting Download Lasted Trend Virus Pattern File.'
    get_virus_pattern(match_virus_pattern_link(pattern_link))
    print 'Download Pattern Finish'
    print 'Deploy Trend Pattern File'
    deploy_pattern()
    print 'Deploy Trend Pattern File Finish'

if __name__ == '__main__':
    main()
